package com.jsu.information.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jsu.information.service.DownLoadService;
import lombok.extern.slf4j.Slf4j;
import com.jsu.information.mapper.DownloadMapper;
import org.example.model.common.dtos.ResponseResult;
import org.example.model.common.enums.RedisCodeEnum;
import org.example.model.common.enums.WebHttpCodeEnum;
import org.example.model.information.pojo.Download;
import org.example.utils.common.FileTools;
import org.example.utils.common.IdsUtils;
import org.example.utils.common.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
@Slf4j
public class DownloadServiceImpl extends ServiceImpl<DownloadMapper, Download> implements DownLoadService {
    @Autowired
    private StringRedisTemplate redisCache;
    private static final ObjectMapper mapper = new ObjectMapper();

    /**
     * 获取所有咨询
     * @return
     */
    @Override
    public ResponseResult getAllDownload() {
        //从redis中获取展商信息
        List<String> news = redisCache.opsForList().range(RedisCodeEnum.DOWNLOAD.getMsg(),0,-1);
        List<Download> downloads = new ArrayList<>();
        if (news.size()==0) {
            //从数据库中获取
            downloads = getBaseMapper().selectList(null);
        }else {
            for (String json:news) {
                Download n = null;
                try {
                    n = mapper.readValue(json, Download.class);
                } catch (JsonProcessingException e) {
                    throw new RuntimeException(e);
                }
                downloads.add(n);
            }
        }
        return ResponseResult.okResult(downloads);
    }

    /**
     * 获取某个单独
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult getDownload(Integer id) {
        //从redis中获取信息
        String key = RedisCodeEnum.DOWNLOAD.getMsg()+id;
        String json = redisCache.opsForValue().get(key);
        Download download = null;
        try {
            download = mapper.readValue(json, Download.class);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        if(!Objects.isNull(download)){
            return ResponseResult.okResult(download);
        }
        //从数据库中获取
        download = getBaseMapper().selectById(id);
        if(Objects.isNull(download)){
            return ResponseResult.errorResult(WebHttpCodeEnum.DATA_NOT_EXIST,"没有该专家");
        }
        return ResponseResult.okResult(download);
    }

    /**
     * 新增下载链接
     *
     * @param download
     * @return
     */
    @Override
    public ResponseResult addDownload(Download download) {
        download.setPkId(IdsUtils.creatCodeFour());
        String key = RedisCodeEnum.DOWNLOAD.getMsg()+download.getPkId();
        String json = null;
        try {
            json = mapper.writeValueAsString(download);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        redisCache.opsForValue().set(key,json);
        int count = getBaseMapper().insert(download);
        if (count<=0) {
            return ResponseResult.errorResult(WebHttpCodeEnum.FAIL,"新增失败");
        }
        return ResponseResult.okResult(200,"新增成功");
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult deleteDownload(Integer id) {
        String key = RedisCodeEnum.DOWNLOAD.getMsg()+id;
        redisCache.opsForValue().getOperations().delete(key);
        int count = getBaseMapper().deleteById(id);
        if (count<=0) {
            return ResponseResult.errorResult(WebHttpCodeEnum.FAIL,"删除失败");
        }
        return ResponseResult.okResult(200,"删除成功");
    }

    /**
     * 修改链接
     *
     * @param download
     * @return
     */
    @Override
    public ResponseResult updateDownload(Download download) {
        String key = RedisCodeEnum.DOWNLOAD.getMsg()+download.getPkId();
        redisCache.opsForValue().getOperations().delete(key);
        String json = null;
        try {
            json = mapper.writeValueAsString(download);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        redisCache.opsForValue().set(key,json);
        int count = getBaseMapper().updateById(download);
        if (count<=0) {
            return ResponseResult.errorResult(WebHttpCodeEnum.FAIL,"修改失败");
        }
        return ResponseResult.okResult(200,"修改成功");
    }

    /**
     * 上传
     *
     * @param file
     * @return
     */
    @Override
    public ResponseResult uploadExcel(MultipartFile file) {
        if (file.isEmpty()) {
            return ResponseResult.errorResult(WebHttpCodeEnum.DATA_NOT_EXIST,"上传的文件不能为空");
        }
        try {
            File excelFile = File.createTempFile("temp", ".xlsx"); // 创建临时文件
            file.transferTo(excelFile); // 将上传的文件保存到临时文件
            List<Download> downloads = FileTools.readExcel(excelFile, Download.class); // 调用读取 Excel 方法
            //批量导入到数据库
            boolean success = saveBatch(downloads);
            //批量存储到redis中
            for (Download n:downloads) {
                String key = RedisCodeEnum.DOWNLOAD.getMsg()+n.getPkId();
                String json = mapper.writeValueAsString(n);
                redisCache.opsForValue().set(key,json);
            }
            if (success) {
                return ResponseResult.okResult(WebHttpCodeEnum.SUCCESS);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseResult.errorResult(WebHttpCodeEnum.FAIL);
        }
        return ResponseResult.errorResult(WebHttpCodeEnum.FAIL);
    }

    /**
     * 导出
     *
     * @param fileName
     * @return
     */
    @Override
    public ResponseResult exportExcel(String fileName) {
        try {
            List<Download> downloads = getBaseMapper().selectList(null); // 获取要导出的数据集合
            int count = FileTools.writeExcel(fileName, Download.class, downloads);// 调用写入 Excel 方法
            if(count>0)
                return ResponseResult.okResult(count);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return ResponseResult.errorResult(WebHttpCodeEnum.FAIL,"暂时没有数据");
    }
}
